package com.dashan.backend.datastore;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.Query;

import com.dashan.backend.DashanException;

public class UserProfileDao extends DaoBase {
    
    public void updateProfile(DsUserProfile profile) {
        return;
    }
    
    @SuppressWarnings("unchecked")
    public List<String> matchProfile(DsUserProfile profile, String[] attrNames) 
       throws IllegalArgumentException, SecurityException, IllegalAccessException, DashanException,
       InvocationTargetException, NoSuchMethodException {
        
        String filter = "";
        try {
            for (String name : attrNames) {
                String[] fieldNames = name.split("\\.");
                
                Object value = DsUserProfile.class
                    .getMethod(toGetterName(fieldNames[0]), new Class<?> [0]).invoke(profile);
                Class<?> type = DsUserProfile.class.getDeclaredField(fieldNames[0]).getType();
                if (value == null || (type == String.class && "".compareTo((String) value) == 0)) {
                    continue;
                }
                if (fieldNames.length == 2) {
                    value = type
                        .getMethod(toGetterName(fieldNames[1]), new Class<?> [0]).invoke(value);
                    type = type.getDeclaredField(fieldNames[1]).getType();
                }
                if (type != String.class) {
                    throw new DashanException("attrNames error!");
                }

                if (value == null || "".compareTo((String) value) == 0) {
                    continue;
                }
                
                filter += String.format(" %s == '%s' &&", name, (String) value);
            }
            if (filter.length() >= 2) {
                filter = filter.substring(0, filter.length() - 2);
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            throw new DashanException("no such field" + e.getMessage());
        }
        
        Query query = pm.newQuery(DsUserProfile.class);
        if (filter.length() > 0) {
            query.setFilter(filter);
        }
        List<DsUserProfile> userList = (List<DsUserProfile>) query.execute();
        
        ArrayList<String> userNameList = new ArrayList<String>();
        for (DsUserProfile p : userList) {
            userNameList.add(p.getUserName());
        }
        userNameList.remove(profile.getUserName());
        return userNameList;
    }
    
    private static String toGetterName(String name) {
        if (name.length() > 0) {
            name = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
        }
        return name;
    }
}
